<?php
declare (strict_types=1);

namespace app\sysuser\controller\subject;

use app\common\controller\SysBackend;
use app\common\enums\SubjectKnowledgeStatusEnum;
use app\common\enums\SubjectQuestionTypeEnum;
use app\common\model\banxi\subject\Subject as SubjectModel;
use app\common\model\banxi\subject\SubjectGrade as SubjectGradeModel;
use app\common\model\banxi\subject\SubjectKnowledge as SubjectKnowledgeModel;
use app\common\model\banxi\subject\SubjectQuestion as SubjectQuestionModel;
use app\common\service\ImportService;
use think\db\exception\DbException;
use think\exception\ValidateException;
use think\facade\Validate;
use think\validate\ValidateRule;

class Question extends SysBackend
{
    protected array $noNeedLogin = [];
    protected array $noNeedPermission = [];

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new SubjectQuestionModel();
    }


    /**
     * 分页查询
     * @return void
     * @throws DbException
     */
    public function listPage(): void
    {
        $param = $this->request->param(['index', 'limit', 'orderBy', "query"]);
        //查询条件解析
        $where = get_query($param);
        //获取分页数据
        $pageParams = get_page_params($param);
        $knowledgeList = [];
        $list = $this->model->where($where)
            ->with([
                'subject' => function ($query) {
                    $query->field('id,name');
                }, 'subjectGrade' => function ($query) {
                    $query->field('id,name');
                }, 'knowledge' => function ($query) {
                    $query->field('id,pid,name');
                }])
            ->order(['id' => 'asc', 'sortNum' => 'desc'])
            ->paginate([
                'page' => $pageParams['page'],
                'list_rows' => $pageParams['limit'],
            ])->each(function ($item) {
                if (!empty($item['knowledge'])) {
                    if (!empty($item['knowledge']['pid'])) {
                        $pid = $item['knowledge']['pid'];
                        $pidKnowledge = SubjectKnowledgeModel::where(['id' => $pid, 'status' => SubjectKnowledgeStatusEnum::E1])->field('id,name')->find();
                        unset($item['knowledge']['pid']);
                        $pidKnowledge['children'] = $item['knowledge'];
                        $item['knowledge'] = $pidKnowledge;
                    } else {
                        $item['knowledge']['children'] = null;
                        unset($item['knowledge']['pid']);
                    }
                }
                $item['option'] = $item['option'] ? json_decode($item['option'], true) : [];
                $item['answer'] = $item['answer'] ? json_decode($item['answer'], true) : [];
            });
        $this->ok('操作成功', result_row($list));
    }

    /**
     * 分页Select查询
     * @return void
     * @throws DbException
     */
    public function listSelectPage(): void
    {
        $param = $this->request->param(['index', 'limit', 'orderBy', "query"]);
        //查询条件解析
        $where = get_query($param);
        //获取分页数据
        $pageParams = get_page_params($param);
        $list = $this->model->where($where)
            ->field('id,name')
            ->order(['id' => 'asc', 'sortNum' => 'desc'])
            ->paginate([
                'page' => $pageParams['page'],
                'list_rows' => $pageParams['limit'],
            ]);
        $this->ok('操作成功', result_row($list));
    }

    /**
     * 查询
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function get()
    {
        $param = $this->request->param(["query" => []]);
        if (empty($param['query'])) {
            $this->fail('请传递你要查询的记录');
        }
        $where = get_query($param);
        $info = $this->model->with([
            'subject' => function ($query) {
                $query->field('id,name');
            }, 'subjectGrade' => function ($query) {
                $query->field('id,name');
            }])->where($where)->find();
        if (empty($info)) {
            $this->fail('记录不存在');
        }
        $info['option'] = $info['option'] ? json_decode($info['option'], true) : [];
        $info['answer'] = $info['answer'] ? json_decode($info['answer'], true) : [];
        $this->ok('操作成功', $info);
    }

    /**
     * 新增或修改
     * @return void
     */
    public function saveOrUpdate()
    {
        $param = $this->request->filter('')->param([
            'id' => null,
            'name' => '',
            'titlePicture' => '',
            'questionType' => 0,
            'subjectId' => 0,
            'subjectGradeId' => 0,
            'subjectKnowledgeId' => 0,
            'difficulty' => 0,
            'option' => [],
            'answer' => [],
            'analysis' => '',
            'sortNum' => 0,
            'status' => 0
        ]);
        try {
            $validate = Validate::rule([
                'name' => ValidateRule::isRequire(null, '请输入题目'),
                // 'titlePicture' => ValidateRule::isRequire(null, '请设置图片'),
                'questionType' => ValidateRule::in([1, 2, 3], '请选择题目类型'),
                'subjectId' => function ($value) {
                    if (SubjectModel::where('id', $value)->count() <= 0) {
                        return '选择科目不存在';
                    }
                    return true;
                },
                'subjectGradeId' => function ($value) {
                    if (SubjectGradeModel::where('id', $value)->count() <= 0) {
                        return '选择年级不存在';
                    }
                    return true;
                },
                'subjectKnowledgeId' => function ($value) {
                    if (SubjectKnowledgeModel::where('id', $value)->count() <= 0) {
                        return '选择知识点不存在';
                    }
                    return true;
                },
                'difficulty' => ValidateRule::isRequire(null, '请设置难度'),
                'option' => function ($value, $data) {
                    if ($data['questionType'] == SubjectQuestionTypeEnum::E3) {
                        return true;
                    }
                    if (!empty($value)) {
                        return true;
                    }
                    return '请设置选项';
                },
                'answer' => function ($value, $data) {
                    if ($data['questionType'] == SubjectQuestionTypeEnum::E3) {
                        return true;
                    }
                    if (empty($value)) {
                        return '请设置选项';
                    }
                    if ($data['questionType'] == SubjectQuestionTypeEnum::E1 && count($value) > 1) {
                        return '单选题只能设置一个答案';
                    }
                    $optionAnswer = array_column($data['option'], 'value');
                    if ($data['questionType'] == SubjectQuestionTypeEnum::E2 && count($value) > count($optionAnswer)) {
                        return '答案数量不能大于选项数量';
                    }
                    for ($i = 0; $i < count($value); $i++) {
                        if (!in_array($value[$i], $optionAnswer)) {
                            return '答案不存在选项中';
                        }
                    }
                    return true;
                },
                'analysis' => ValidateRule::isRequire(null, '请设置难度'),
                'sortNum' => ValidateRule::isNumber(null, '请输入正确的排序数字'),
                'status' => ValidateRule::in([1, 2], '请输入正确的状态')
            ]);
            if (!$validate->check($param)) throw new ValidateException($validate->getError());
            $this->model->saveOrUpdate($param);
        } catch (ValidateException $exception) {
            $this->fail($exception->getMessage());
        }
        $this->ok('操作成功', [], self::NOTIFICATION);
    }


    public function del()
    {
        $param = $this->request->param(['ids' => []]);
        try {
            $validate = Validate::rule([
                'ids' => ValidateRule::isRequire(null, '请选择你要删除的记录'),
            ]);
            if (!$validate->check($param)) throw new ValidateException($validate->getError());
            SubjectQuestionModel::destroy(function ($query) use ($param) {
                $query->whereIn('id', $param['ids']);
            });
        } catch (ValidateException $exception) {
            $this->fail($exception->getMessage());
        }
        $this->ok('操作成功', [], self::NOTIFICATION);
    }

    /**
     * 随机题
     * @return void
     */
    public function randomQuestion()
    {
        $param = $this->request->param(['subjectKnowledgeId' => 0, 'randomNum' => 1]);
        try {
            $validate = Validate::rule([
                'subjectKnowledgeId' => ValidateRule::isRequire(null, '请选择你要查询知识点'),
                'randomNum' => ValidateRule::isRequire(null, '请设置你要随机的数量'),
            ]);
            if (!$validate->check($param)) throw new ValidateException($validate->getError());
            $res = $this->model->randomQuestion($param['subjectKnowledgeId'], $param['randomNum']);
        } catch (ValidateException $exception) {
            $this->fail($exception->getMessage());
        }
        $this->ok('成功', $res);
    }

    public function getQuestionTemplate()
    {
        $path = '/template/题库模板.xlsx';
        $filePath = app()->getRootPath() . 'public' . $path;
        // 检查文件是否存在
        if (!file_exists($filePath)) {
            $this->fail('文件不存在');
        }
        $domain = $this->request->domain();
        $this->ok('success', ['filePath' => $domain . $path]);
    }

    public function import()
    {
        $file = $this->request->file('file');
        if (!$file) {
            $this->fail(__('请选择导入的文件'));
        }

        $importService = new ImportService();
        $res = $importService->questionImport($file);
        if (!$res) {
            $this->fail(__($importService->getError()));
        }
        $this->success(__('导入成功'), $res);

    }
}
